<template>
	<view>
		<view class="tree-item" :class="{'m-bot20': item.top}" v-for="item in treeData" :key="item.id">
			<view class="item-title" @click="nodeClick(item)">
				<image class="icon m-right20" :src="staticImg + 'folder.png'" mode="aspectFit" v-if="item.flagDir"></image>
				<view class="flex-1 size32 ellipsis_1">{{ item.name }}</view>
				<text class="iconfont icon-a-zujian32 size24 color-999" :class="{'active': isOpen(item.id)}" v-if="item.children.length"></text>
			</view>
			<view class="item-children" v-if="item.children && item.children.length" v-show="isOpen(item.id)">
				<tree :treeData="item.children" @node-click="handleNodeClick" />
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, defineEmits } from 'vue'
	import { staticImg } from '@/utils/config.js'
	import tree from './tree.vue'

	const props = defineProps({
		treeData: {
			type: Array,
			default: () => []
		}
	})

	const expandedKeys = ref([]) // 当前展开节点的id

	const emit = defineEmits(['node-click'])

	const nodeClick = (item) => {
		emit('node-click', item)
		if(item.children && item.children.length) { // 动态展开收起
			let index = expandedKeys.value.indexOf(item.id)
			if(index > -1) return expandedKeys.value.splice(index, 1)
			expandedKeys.value.push(item.id)
		}
	}

	const handleNodeClick = (item) => { // 向上层组件触发事件
		emit('node-click', item)
	}

	const isOpen = (id) => {
		return expandedKeys.value.includes(id)
	}
</script>

<style lang="scss" scoped>
	.tree-item {
		background: #FFFFFF;
		border-radius: 20rpx;
		.item-title {
			height: 120rpx;
			padding: 0 20rpx;
			display: flex;
			align-items: center;
			.icon {
				width: 48rpx;
				height: 48rpx;
			}
			.icon-a-zujian32 {
				transform: rotate(0);
				transition: transform .3s;
				&.active {
					transform: rotate(90deg);
				}
			}
		}
		.item-children {
			padding-left: 20rpx;
		}
	}   
</style>
